package com.sptpc.library.service;

import com.sptpc.library.model.Borrowing;
import com.sptpc.library.model.vo.BorrowingVo;
import com.sptpc.library.repository.BorrowingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BorrowingService {
    @Autowired
    private BorrowingRepository borrowingRepository;

    // 查
    //得到所有图书信息
    public List<Borrowing> findAll(){
        return borrowingRepository.findAll();
    }

    public List<Borrowing> findByUserId(Long userId) {
        return borrowingRepository.findByUserId(userId);
    }

    public Borrowing findByBorrowId(Long borrowId) {
        return borrowingRepository.findByBorrowId(borrowId);
    }

    public Borrowing update(BorrowingVo borrowingVo) {
        Optional<Borrowing> oldBorrowing = borrowingRepository.findById(borrowingVo.getBorrowId());
        if (oldBorrowing.isPresent()) {
            Borrowing borrowing = oldBorrowing.get();
//            borrowing.setBorrowId(borrowingVo.getBorrowId());
//            borrowing.setUserId(borrowingVo.getUserId());
//            borrowing.setUserName(borrowingVo.getUserName());
//            borrowing.setBookId(borrowingVo.getBookId());
//            borrowing.setBookName(borrowingVo.getBookName());
            borrowing.setReturnBook(borrowingVo.getReturnBook());
            return borrowingRepository.saveAndFlush(borrowing);
        } else {
            return null;
        }
    }


    public String deleteByBorrowId(Long borrowId) {
        Optional<Borrowing> borrowing = borrowingRepository.findAllByBorrowId(borrowId);
        if (borrowing.isPresent()) {
            borrowingRepository.delete(borrowing.get());
            return "删除成功";
        } else {
            return null;
        }
    }

    public List<Borrowing> findAllByUserName(String userName) {
        return borrowingRepository.findAllByUserName(userName);
    }
}
